<template>
	<app-layout>
		<view class="mine tn-safe-area-inset-bottom">
			<!-- 顶部自定义导航 -->
			<tn-nav-bar :isBack="!!1" :bottomShadow="false">尿检录入</tn-nav-bar>
			<view class="about__wrap" :style="{paddingTop: vuex_custom_bar_height + 'px'}">
				<view class="tn-padding-bottom-xl tn-bg-white">
					<tn-list-view :card="true" unlined="all">
						<block>
							<view class="tn-padding ">
								<tn-form :labelWidth="150" :model="form" ref="uForm" :errorType="['message']"
									v-show="xduser">
									<tn-form-item label="被检测人" prop="xdusername" :required="true">
										<view class="">
											{{xduser.username}}
										</view>
									</tn-form-item>
									<tn-form-item label="通知日期" prop="tztime" :required="true">
										<tn-input v-model="form.tztime" type="select" :selectOpen="tztimeshow"
											placeholder='选择通知日期' @click="tztimeshow = true" />
										<tn-calendar :safeAreaInsetBottom="!!1" :toolTips="`请选择通知日期`"
											v-model="tztimeshow" :changeYear="false" mode="date"
											@change="tzselect"></tn-calendar>
									</tn-form-item>
									<tn-form-item label="检测时间" prop="njtime" :required="true">
										<tn-input v-model="form.njtime" placeholder='正在获取检测时间' disabled />
									</tn-form-item>

									<tn-form-item label="检测地点" prop="njdd" :required="true">
										<tn-input v-model="form.njdd" type="select" :selectOpen="addressShow"
											placeholder='选择检测地点' @click="addressShow = true" />
										<tn-select labelName="details" valueName="id" v-model="addressShow"
											:list="addresslist" @confirm="addressconfirm"></tn-select>
									</tn-form-item>

									<tn-form-item label="选择村委" prop="njddok" v-if="form.placeid==97" :required="true">
										<tn-input v-model="form.njddok" type="select" :selectOpen="cityShow"
											placeholder='选择村委(社区)' @click="cityShow = true" />
										<tn-select labelName="name" valueName="id" v-model="cityShow" :list="citylist"
											@confirm="cityconfirm" :searchShow="true"></tn-select>
									</tn-form-item>
									<tn-form-item label="选择城市" prop="pcaeraname" :required="true"
										v-if="form.placeid=='172'|| form.placeid=='100'|| form.placeid=='99' || form.placeid=='98'">
										<tn-input v-model="form.pcaeraname" type="select" :selectOpen="dqShow"
											placeholder='选择城市' @click="dqShow = true" />

										<tn-picker mode="region" v-model="dqShow" @confirm="dqconfirm"></tn-picker>
									</tn-form-item>

									<tn-form-item label="输入地点" prop="elaeraname" :required="true"
										v-if="form.placeid=='172'|| form.placeid=='100'|| form.placeid=='99' || form.placeid=='98'">
										<tn-input v-model="form.elaeraname" type="textarea" :border="!!0" :height="100"
											placeholder='详细地址' />
									</tn-form-item>


									<tn-form-item label="检测种类" prop="njtype" :required="true">
										<view class="tn-flex tn-flex-wrap">
											<tn-checkbox-group @change="ilkchange">
												<tn-checkbox v-model="item.checked" v-for="(item, index) in ilklist"
													:key="index" :name="item.num">{{item.details}}</tn-checkbox>
											</tn-checkbox-group>
										</view>
									</tn-form-item>
									<tn-form-item label="检测结果" prop="njresult" :required="true">
										<view v-if="ilkresult.length<1" class="tn-flex tn-flex-wrap">
											<tn-input disabled placeholder='选择检测种类' />
										</view>
										<view class="ilkresult">
											<view v-for="(res, index) in ilkresult" :key="index"
												class="tn-flex  tn-flex-col-center tn-flex-row-right">
												<template>
													<view class="nm">
														{{res.name}}
													</view>
													<view class="yx"
														:class="res.result===0 && 'tn-bg-green tn-color-white'"
														@click="setilk(index,0)">
														阴性
													</view>
													<view class="yx"
														:class="res.result===1 && 'tn-bg-red tn-color-white'"
														@click="setilk(index,1)">
														阳性
													</view>
												</template>
											</view>
										</view>
									</tn-form-item>
									<tn-form-item label="检测照片" prop="jczp" :required="true">
										<view @click="showloading">
											<tn-image-upload :formData="formData" :action="action" @on-error="uperror"
												uploadText="拍照上传" :isdd="isdd" :autoUpload="!!1" @on-change="upchange"
												@on-success="upsuccess" @on-choose-complete="choosecomplete"
												:showUploadList="setting.showUploadList"
												:sourceType="setting.sourceType"></tn-image-upload>
										</view>
									</tn-form-item>


									<tn-form-item label="检测人" prop="njuser" :required="true">
										<tn-input v-if="form.placeid==172" v-model="form.njuser" type="text"
											placeholder='请输入检测人' />
										<view v-else class="tn-flex tn-flex-wrap">
											<tn-checkbox-group @change="userchange">
												<tn-checkbox v-model="item.checked" v-for="(item, index) in witness"
													:key="index"
													:name="item.zhanghaouser">{{item.zhanghaouser}}</tn-checkbox>
											</tn-checkbox-group>
										</view>
									</tn-form-item>

								</tn-form>
							</view>
						</block>
					</tn-list-view>
				</view>
			</view>
			<bottom-btn @save="save" @submit="submit"></bottom-btn>
			<view class='tn-tabbar-height'></view>
		</view>
	</app-layout>
</template>

<script>
	import locationmixin from '@/libs/mixin/location_mixin.js'
	import {
		mapGetters,
		mapState
	} from 'vuex';

	export default {
		name: 'checkdetail',
		mixins: [locationmixin],
		data() {
			return {
				//签名板
				show: false,
				//通知时间
				tztimeshow: false,

				form: {
					mfid: '',
					tztime: '',
					njtime: '',
					cityid: '',
					njdd: '',
					placeid: '',
					pcaeraname: '',
					elaeraname: '',
					njddok: '',

					sfyx: 0,

					jczp: '',
					//任务id
					tid: 0,
					//异地模式id
					cid: 0,
					//检测人
					njuser: '',

					//尿检结果
					njtype: '',
					njresult: '',
				},
				formData: {},
				rules: {
					tztime: [{
						required: true,
						message: '请选择通知时间',
						trigger: 'blur,change'
					}],
					njdd: [{
						required: true,
						message: '请选择地点',
						trigger: 'blur,change'
					}],
					jczp: [{
						required: true,
						message: '请上传检测照片',
						trigger: 'blur,change'
					}],
					njtype: [{
						required: true,
						message: '请选择检测种类',
						trigger: 'blur,change'
					}],
					njresult: [{
						required: true,
						message: '请选择检测结果',
						trigger: 'blur,change'
					}],
					njuser: [{
						required: true,
						message: '请选择检测人',
						trigger: 'blur,change'
					}],
					pcaeraname: [{
						required: true,
						message: '请选择城市',
						trigger: 'blur,change'
					}],
					elaeraname: [{
						required: true,
						message: '请输入详细地址',
						trigger: 'blur,change'
					}],
					njddok: [{
						required: true,
						message: '请选择村委',
						trigger: 'blur,change'
					}],

				},

				//选择城市
				dqShow: false,
				//当前可选见证人列表
				witness: [],
				//已选见证人
				select_witness_list: [],
				select_witness: '',

				list: [],

				addressShow: false,
				addresslist: [],
				address_detail: '',

				cityShow: false,
				citylist: [],
				typeShow: false,
				type: '',
				typelist: [{
					id: 1,
					name: '定期'
				}, {
					id: 2,
					name: '突击'
				}],
				//检查类型
				ilklist: [],
				ilkresult: [],
				timer: '',
			}
		},

		computed: {
			...mapState({
				userinfo: state => state.userinfo
			})
		},

		watch: {
			photo(nval, oval) {
				this.form.jczp = nval
			},
			//监听检测类型
			ilkresult: {
				handler(nval, oval) {
					let njtype = '',
						njresult = '';
					nval.forEach(i => {
						njtype = `${njtype===''?'':njtype+','}${i.num}`
						njresult = `${njresult ===''?'':njresult+','}${i.result}`
					})
					this.form.njtype = njtype;
					this.form.njresult = njresult;
				},
				deep: true
			}
		},
		onLoad(options) {
			let t = this;
			if (options.mfid) {
				//普通模式
				this.form.mfid = options.mfid ? options.mfid : this.form.mfid;
				//任务模式
				this.form.tid = options.tid ? options.tid : this.form.tid;
				//异地任务模式
				this.form.cid = options.cid ? options.cid : this.form.cid;
				this.formData = {
					mfid: this.form.mfid,
					type: 2
				}
			} else {
				uni.showModal({
					title: '提示',
					content: '用户ID不存在，请稍后再试',
					showCancel: false,
					success() {
						t.goBack()
					}
				})
			}
			//获取人脸识别用户ID
			let checkid = t.$storage.getStorageSync('checkid');
			if (checkid != this.form.mfid) {
				uni.showModal({
					title: '提示',
					content: '未获取到人脸核验信息，请重试',
					showCancel: false,
					success() {
						t.goBack()
					}
				})
			}
			this.getvillages()
			this.getplace()
			this.getdetection()
			this.getilklist()
			if (this.timer) {
				clearInterval(this.timer)
			}
			this.timer = setInterval(() => {
				t.form.njtime = t.$utils.datetime('Y-m-d h:i:s')
			}, 1000)

		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onShow() {
			let t = this;
			if (!t.userinfo) {
				t.$user.getInfo()
			}
		},
		methods: {

			save() {
				let t = this;
				if (t.ilkresult.find(il => il.result === '')) {
					this.$t.message.toast('请完善检测结果')
				}
			},
			userchange(e) {
				let usernames = '';
				e.forEach(i => {
					usernames = `${usernames===''?'':usernames+','}${i}`
				})
				this.form.njuser = usernames;
			},
			setilk(idx, res) {
				let t = this,
					njresult = '';
				this.ilkresult[idx].result = res
			},
			ilkchange(e) {

				let tempres = this.$utils.deepClone(this.ilkresult),
					njtype = '';
				this.ilkresult = [];
				e.forEach(i => {
					let old = tempres.find(ilk => ilk.num == i);
					let real = this.ilklist.find(rea => rea.num == i);
					this.ilkresult.push({
						name: real.details,
						num: real.num,
						result: old ? old.result : ''
					})
				})
			},

			submit() {
				let t = this;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						// 验证通过
						console.log('验证通过')
						if (t.form.placeid == '172' || t.form.placeid == '100' || t.form.placeid == '99' || t.form
							.placeid == '98') {
							t.form.njddok = `${t.form.pcaeraname}${t.form.elaeraname}`;
						}
						if (t.form.placeid == '95' || t.form.placeid == '96') {
							t.form.njddok = ''
						}

						if (t.ilkresult.find(il => il.result === '')) {
							this.$t.message.toast('请完善检测结果')
							return false
						}
						let sfyx = t.ilkresult.filter(il => il.result == 1)
						if (sfyx.length > 0) {
							t.form.sfyx = 1
						}
						t.add()
					} else {
						// 验证失败
						console.log('验证失败')
					}
				})
			},
			add(param) {
				let t = this;
				this.$t.message.loading('提交中');
				this.$request({
					url: this.$api.urinecheck.add,
					data: t.form,
					method: 'POST'
				}).then(response => {
					t.$t.message.closeLoading();
					if (response.code === 0) {
						let url = `/discoveryPages/urinecheck/list?mfid=${t.form.mfid}`
						if (t.form.tid) {
							url = `/discoveryPages/wait/urinelist`
						}
						//如果是异地任务 添加完返回异地任务列表
						if(t.form.cid){
							url = `/discoveryPages/wait/otherlist`
						}
						uni.showModal({
							title: '',
							content: response.msg,
							showCancel: false,
							success() {
								uni.redirectTo({
									url: url
								});
							}
						});
					} else {
						uni.showModal({
							title: '',
							content: response.msg,
							showCancel: false,
						});
					}
				}).catch((msg) => {
					t.$t.message.closeLoading();
				});
			},

			tzselect(e) {
				console.log(e)
				this.form.tztime = e.date
			},

			dqconfirm(e) {
				console.log('dqconfirm', e)
				this.form.pcaeraname = `${e.province.label}${e.city.label}${e.area.label}`
			},
			addressconfirm(e) {
				let guishu = '';
				if (this.userinfo.usergroup == 'jbd' || this.userinfo.usergroup == 'admin') {
					guishu = this.xduser.gsxz
				} else {
					guishu = this.userinfo.guishu
				}
				if ((e[0].value == 95 || e[0].value == 96) && this.userinfo) {
					this.form.njdd =
						`${guishu.replace('街道','').replace('镇','').replace('乡','')}${e[0].label}`
				} else {
					this.form.njdd = e[0].label
				}
				this.form.placeid = e[0].value
				this.form.njddok = ''
			},
			cityconfirm(e) {
				console.log(22, e)
				this.form.njddok = e[0].label
				this.form.cityid = e[0].value
			},

			//获取村委关联列表
			getvillages() {
				this.$t.message.loading('加载中');
				//获取村委关联列表
				this.$request({
					url: this.$api.common.villages,
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.citylist = response.list;

					}
				});
			},

			//获取检测地点
			getplace() {
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.place,
					method: 'POST',
					data: {
						//类型 1尿检地点 2走访地点
						type: 1
					}
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.addresslist = response.list;
					}

				}).catch(() => {
					this.$t.message.closeLoading();
				});
			},

			//获取检测人员
			getdetection() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.detection,
					data: {
						mfid: t.form.mfid
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.witness = response.list;
					}
				});
			},

			//获取检测种类
			getilklist() {
				let t = this;
				this.$t.message.loading('加载中');
				this.$request({
					url: this.$api.common.typelist,
					data: {
						did: 1
					},
					method: 'POST'
				}).then(response => {
					this.$t.message.closeLoading();
					if (response.code === 0) {
						this.ilklist = response.list;
						this.ilklist.forEach(i => {
							i.result = ''
						})
					}
					this.$t.message.closeLoading();
				});
			},

			// 弹出SignBoard
			showSignBoard() {
				this.show = true
			},
			// 切换画笔颜色
			colorChange(event) {
				switch (event.index) {
					case 0:
						this.signSelectColor = ['#2f2f2f', '#d5540a']
						break
					case 1:
						this.signSelectColor = ['#838383', '#2074D4']
						break
				}
				this.showSignBoard()
			},
			// 切换旋转内容
			rotateChange(event) {
				this.rotate = event.index === 0 ? false : true
				this.showSignBoard()
			},

			// 保存签名
			saveSign(e) {
				// console.log(e);
				this.imageSrc = e
				this.show = false
			},
			// 关闭签名板
			closeSign() {
				this.show = false
			},

			// 返回前判断是否已经关闭了签名板
			beforeBack() {
				return new Promise((resolve, reject) => {
					if (!this.show) {
						resolve()
						return
					}
					this.$tn.message.modal('操作提示', '当前已经打开了签名板，是否确认需要关闭', () => {
						resolve()
					}, true, () => {
						reject()
					})
				})
			}

		}
	}
</script>

<style lang="scss" scoped>
	.box {
		padding: 15rpx;
	}

	.yx {
		padding: 0 20rpx;
		margin: 0 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		border: 1rpx solid #555555;
		border-radius: 10rpx;
		height: 50rpx;
	}

	.nm {
		max-width: 250rpx;
		text-align: right;
		padding-right: 10px;
	}

	.ilkresult {
		display: flex;
		flex-direction: column;
		width: 100%;
		align-items: flex-end;
	}

	/* 底部安全边距 start*/
	.tn-tabbar-height {
		min-height: 120rpx;
		height: calc(140rpx + env(safe-area-inset-bottom) / 2);
		height: calc(140rpx + constant(safe-area-inset-bottom));
	}

	.sign {
		width: 100%;
		height: 200rpx;
	}

	.photo {
		width: 100rpx;
		height: 120rpx;
		margin: 10rpx;
	}

	/* 用户头像 start */
	.logo-image {
		width: 200rpx;
		height: 200rpx;
		position: relative;
		overflow: hidden;
		border-radius: 50%;
	}
</style>